<template>
  <div class="app-container">
    <div class="filter-container" id="filter-container-TaskFlowDs">
      <vxe-form
          :data="listQuery"
          style="font-weight: bold"
          title-align="right"
          title-width="120"
          title-colon
      >
        <vxe-form-item title="数据库类型" field="type" span="6" >
          <template #default>
            <el-input
                    v-model="listQuery.type"
                    size="small"
                    class="filter-item"
                    @keyup.enter.native="handleFilter"
                    clearable
            />
          </template>
        </vxe-form-item>
        <vxe-form-item title="名称" field="name" span="6" >
          <template #default>
            <el-input
                    v-model="listQuery.name"
                    size="small"
                    class="filter-item"
                    @keyup.enter.native="handleFilter"
                    clearable
            />
          </template>
        </vxe-form-item>
        <vxe-form-item align="right" span="24" collapse-node>
          <template #default>
            <el-button :loading="queryLoading" class="filter-item" size="small" type="primary" plain icon="el-icon-search" @click="handleFilter">
              查询
            </el-button>
          </template>
        </vxe-form-item>

      </vxe-form>
    </div>


    <vxe-toolbar style="padding-left: 10px;margin-top: 10px" perfect>
      <template v-slot:buttons>
        <el-button v-show="hasPermission(['flow:taskFlowDs:create'])" class="filter-item" size="small" type="primary" plain icon="el-icon-plus" @click="handleCreate">
          添加
        </el-button>
      </template>
    </vxe-toolbar>



    <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        :show-summary="false"
        :summary-method="getSummaries"
        style="width: 100%;"
        :height="tableHeight"
        @sort-change="sortChange"
        @row-click="handleRowClick"
    >
      <el-table-column align="center" type="index" width="45" label="序号">
        <template slot-scope="scope">
          <span> {{(listQuery.page - 1) * listQuery.limit + scope.$index + 1}}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="数据库类型"
        prop="type"
        align="center"
        min-width="100"
        :fixed="false">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.type" class="edit-input" size="mini" />
              <span v-else>{{ row.type }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="名称"
        prop="name"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.name" class="edit-input" size="mini" />
              <span v-else>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="连接URL"
        prop="url"
        align="left"
        min-width="500"
        :fixed="false">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.url" class="edit-input" size="mini" />
              <span v-else>{{ row.url }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="用户名"
        prop="username"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.username" class="edit-input" size="mini" />
              <span v-else>{{ row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="密码"
        prop="password"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.password" type="password" size="mini" />
              <span v-else>******</span>
        </template>
      </el-table-column>

    <!--  <el-table-column
        label="扩展数据"
        prop="extend"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <el-input v-if="row.edit" v-model="row.extend" class="edit-input" size="mini" />
              <span v-else>{{ row.extend }}</span>
        </template>
      </el-table-column>-->

      <el-table-column
        label="创建日期"
        prop="createTime"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="创建人"
        prop="creator"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.creator }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="修改日期"
        prop="updateTime"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="修改人"
        prop="updator"
        align="center"
        min-width="150"
        :fixed="false">
        <template slot-scope="{row}">
              <span>{{ row.updator }}</span>
        </template>
      </el-table-column>


      <!--操作Button + 页面级权限控制:hasPermission -->
      <el-table-column v-show="hasPermission(['flow:taskFlowDs:update','flow:taskFlowDs:delete'])" fixed="right" label="操作" align="center" min-width="180">
        <template slot-scope="{row,$index}">
          <el-button v-show="row.edit" type="success" icon="el-icon-close" title="取消" size="mini" @click="cancelEdit(row)"></el-button>
          <el-button v-if="row.edit" type="success" icon="el-icon-check" title="保存" size="mini" @click="confirmEdit(row)"></el-button>
          <el-button v-show="hasPermission(['flow:taskFlowDs:update'])" v-else type="primary" icon="el-icon-edit" title="编辑" size="mini" @click="row.edit=!row.edit">
          </el-button>
          <el-button v-show="hasPermission(['flow:taskFlowDs:delete'])" type="danger" icon="el-icon-delete" title="删除" size="mini" @click="handleDelete(row)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <form-details ref="formDetails" :row="row" :isModule="true" @createResult="createResult"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {fetchList, updateApi, deleteApi} from './api'
import waves from '@/directive/waves' // waves directive
import { parseTime, reorgQueryParams, resizeTableHeight } from '@/utils'
import checkPermission from '@/utils/permission'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import FormDetails from './form-details.vue' // add form form dialog
// 从当前View的私有数据对象中取数据
import { pickerOptions, pickerOptionsSingleDate } from './data'
// 导入多选项组件
import SelectOption from '@/views/coding/components/SelectOption'
import {theadOptions} from './data' // excel 列数据

export default {
    name: 'TaskFlowDs-ListLineEdit',

    components: { Pagination, FormDetails, SelectOption },
    directives: { waves },

    props: {
        // 作为子组件时，需要回调传值；应用场景：一对多关联查询时，点击左边查询列表，传值给右边子列表，查询子列表结果
        isModule: {
            type: Boolean,
            default: false
        },
        // 当作为侧边查询结果显示的右子组件时，接收父组件的传值，watch中查询
        parentRow: Object
    },

    filters: {
        statusFilter(status) {
            const statusMap = {
                published: 'success',
                draft: 'info',
                deleted: 'danger'
            }
            return statusMap[status]
        }
    },

    data() {
        return {
          tableKey: 0,
          list: [],
          total: 0,
          footer: [],
          listLoading: false,
          queryLoading: false,
          downloadLoading: false,
          listQuery: {
              page: 1,
              limit: 20,
              sort:'-id'
          },
          importanceOptions: [1, 2, 3],
          sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
          statusOptions: ['published', 'draft', 'deleted'],
          dialogFormVisible: false,
          dialogStatus: '',
          textMap: {
              update: '编辑',
              create: '新增'
          },
          pickerOptions: pickerOptions,
          pickerOptionsSingleDate: pickerOptionsSingleDate,
          row: {},
          tableHeight:0, // 表格高度
          filterContainerHeight: 0, // 查询容器高度
          clientHeight: 0, // 浏览器高度
          // excel
          excelFilename:'excel报表',
          excelDataList:[],
          excelTotal:0,
          excelRate:'',
        }
    },

    computed: {
        /*// button is show
        hasAddBtn() {
          if ( this.btnIdList.filter(id=>id===1).length!=0 ) {
            return true
          }
          return false
        },
        hasEditBtn() {
          if ( this.btnIdList.filter(id=>id===2).length!=0 ) {
            return true
          }
          return false
        },
        hasDelBtn() {
          if ( this.btnIdList.filter(id=>id===3).length!=0 ) {
            return true
          }
          return false
        },
        hasDownloadBtn() {
          if ( this.btnIdList.filter(id=>id===4).length!=0 ) {
            return true
          }
          return false
        }*/
    },

    watch: {
        // 当作为侧边查询的子组件时，接收父组件的传值，watch中查询
        parentRow(pRow) {
            this.listQuery[pRow.classInstance+'Id'] = pRow.id // parantId, 需修改成主表ID。******
            this.handleFilter()
        }
    },

    created() {
        this.getList()
    },

    mounted () {
        // 浏览器、元素大小变化时，动态调整table高度
        resizeTableHeight(this, 'filter-container-TaskFlowDs',235)
    },

    methods: {
        // 页面级权限控制，调用方法如：hasPermission(['a2user:delete'])
        hasPermission(needPermisions) {
          return checkPermission(needPermisions)
        },
        // 刷新
        getList() {
            this.listLoading = true
            this.getListNoLoading()
        },
        getListNoLoading() {
            this.queryLoading = true
            // 重组查询条件
            const params = Object.assign({}, this.listQuery)
            reorgQueryParams(params)
            // 查询
            fetchList(params).then(result => {
                if (!result.success) {
                    this.notify(result)
                    this.queryLoading = false
                    this.listLoading = false
                    return
                }
                const items = result.map.rows
                this.total = result.map.total
                // 备份数据，编辑还原用
                this.list = items.map(v => {
                    this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
                    v.original = Object.assign({}, v)
                    return v
                })
                // footer
                if (result.map.footer && result.map.footer.length>0) {
                  this.footer = result.map.footer
                }
                this.queryLoading = false
                this.listLoading = false
                ++this.tableKey
            })
        },
        // 从第一页开始查询
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        // 排序
        sortChange(data) {
          const { prop, order } = data
          let ascDesc = "-"
          if (order === 'ascending') {
            ascDesc = "+"
          }
          this.listQuery.sort = ascDesc+prop
          this.handleFilter()
        },
        // SUM
        getSummaries(param) {
            if (this.footer.length == 0) {
              return []
            }
            const sums = [];
            const { columns, data } = param;
            columns.forEach((column, index) => {
                if (index === 1) {
                    sums[index] = '合计';
                    return;
                }
                if (this.footer[0][column.property] && typeof this.footer[0][column.property]!=="object") {
                    sums[index] = this.footer[0][column.property]
                    return;
                }
            });
            return sums;
        },

        // download excel
        handleDownload() {
          // 重组查询条件
          const params = Object.assign({}, this.listQuery)
          params.page = 1
          params.limit = 100
          reorgQueryParams(params)
          // 查询, 调用生成Excel
          this.downloadLoading = true
          this.excelDataList = []
          this.fetchExcelList(params)
        },
        // invoke api
        fetchExcelList(params) {
          fetchList(params).then(result => {
            if (!result.success) {
              this.notify(result)
              this.downloadLoading = false
              return
            }
            // 分批查询，做进度条
            result.map.rows.forEach(item=>{
              this.excelDataList.push(item)
            })
            this.excelTotal = result.map.total

            let pageCount = parseInt(this.excelTotal/params.limit)
            if (this.excelTotal%params.limit>0) {
              pageCount = pageCount+1
            }
            let rate = params.page/pageCount
            if (rate>1)rate=1
            this.excelRate = parseInt(rate*100) + '%'
            //check is continue
            if (rate<1) {
              params.page = params.page+1
              this.fetchExcelList(params)
            }else{
              // 生成Excel
              this.makeExcel()
            }
          })
        },
        // 生成Excel
        makeExcel() {
          //excel 列
          let properties = []
          let labels = []
          theadOptions.forEach(item=>{
            if (item.show) {
              properties.push(item.property)
              labels.push(item.label)
            }
          })
          import('@/excel/excelexport').then(excel => {
            const tHeader = labels //[ '名称', '创建时间', '创建人']  // excel中显示的列名
            const filterVal = properties //[ 'merchantName', 'createdate', 'createman'] // excel中显示哪些列，与tHeader对应
            const list = this.excelDataList
            const data = this.formatJson(filterVal, list)

            //excel 支持多sheet
            let filename = this.excelFilename
            let titleList = [] //['垃圾分类评分', '垃圾分类评分明细']
            let headerList = [tHeader]
            let dataList = [data]
            let sheetNames = ['sheet1']
            let autoWidth = true
            excel.export2Excel(titleList,headerList,dataList,filename,sheetNames, autoWidth)

            this.excelRate = ''
            this.downloadLoading = false
          })
        },
        // 处理数据类型
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else if(j.indexOf('.')!= -1){
                    let obj = j.split('.')[0]
                    let objProperty = j.split('.')[1]
                    return this.$options.filters['getJsonName'](v[obj],objProperty)
                } else {
                    return v[j]
                }
            }))
        },
        // 添加操作 start
        handleCreate() {
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            // 消除上次出现的验证信息
            this.$nextTick(() => {
                this.$refs['formDetails'].clearValidate()
                this.$refs['formDetails'].resetTemp()
                this.$refs['formDetails'].defaultTemp()
                // 主从表
                this.$refs['formDetails'].setMasterId(this.parentRow)
            })
        },
        // 调用子组件操作数据
        createData() {
            this.$refs['formDetails'].createData()
        },
        // 子组件操作成功，回调此方法，关闭弹框、刷新
        createResult() {
            this.dialogFormVisible = false
            this.handleFilter()
        },
        // 编辑操作 start
        cancelEdit(row) {
            // 还原原始值
            Object.keys(row).forEach(key => {
                if (key !== 'original' && key !== 'edit') {
                    row[key] = row.original[key]
                }
            })
            row.edit = false
            // row.original.edit = false
            this.$message({
                message: '数据恢复到原始值',
                type: 'warning'
            })
        },
        confirmEdit(row) {
            const param = Object.assign({}, row)
            param.original = {}
            updateApi(param).then((r) => {
                this.notify(r)
                if (r.success) {
                    row.edit = false
                    // 原始值：更新成最新输入值
                    Object.keys(row).forEach(key => {
                        if (key !== 'original' && key !== 'edit') {
                            row.original[key] = row[key]
                        }
                    })
                    this.getListNoLoading()
                }
            })
        },
        // 删除操作
        handleDelete(row) {
            this.$confirm('确认删除吗？')
                .then(_ => {
                    // delete api
                    deleteApi({ id: '' + row.id }).then((r) => {
                        this.notify(r)
                        if (r.success) {
                            this.getList()
                        }
                    })
                    // end
                })
                .catch(_ => {})
        },
        // 行点击事件；应用场景：一对多关联查询时，点击左边查询列表，传值给右边子列表，查询子列表结果
        handleRowClick(row, column, event) {
            // 从父组件调用此方法，进行回调下
            if (this.isModule) {
              row.classInstance = 'ttfTaskFlowDs'
              this.$emit('input', row)
            }
        },
        getSortClass: function(key) {
            const sort = this.listQuery.sort
            return sort === `+{key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 40%;
  }
</style>
